package com.mixed.mixedserver.game.network;

import com.mixed.mixedserver.config.NettyConfig;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.timeout.IdleStateHandler;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class GameChannelInitializer extends ChannelInitializer<SocketChannel> {
    
    @Resource
    private NettyConfig nettyConfig;
    
    @Resource
    private GameServerHandler gameServerHandler;
    
    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        
        // HTTP 编解码器
        pipeline.addLast("httpServerCodec", new HttpServerCodec());
        
        // HTTP 对象聚合器，用于处理完整的 HTTP 请求
        pipeline.addLast("httpObjectAggregator", new HttpObjectAggregator(65536));
        
        // WebSocket 压缩处理器
        pipeline.addLast("webSocketCompression", new WebSocketServerCompressionHandler());
        
        // WebSocket 协议处理器
        pipeline.addLast("webSocketProtocol", new WebSocketServerProtocolHandler("/", null, true));
        
        // 心跳检测
        pipeline.addLast("idleStateHandler", new IdleStateHandler(
            nettyConfig.getHeartbeat().getReaderIdleTime(),
            nettyConfig.getHeartbeat().getWriterIdleTime(),
            nettyConfig.getHeartbeat().getAllIdleTime(),
            TimeUnit.SECONDS
        ));
        
        // WebSocket 消息处理器
        pipeline.addLast("webSocketHandler", new WebSocketGameHandler(gameServerHandler));
    }
}